<template>
	<view class="flex-1 flex-col justify-between">
		<view class="flex-1 flex-col">
			<view class="flex-1">
				<scroll-view scroll-y="true" class="flex-1 py-1" :scroll-into-view="scrollIntoViewId" @scroll="onScroll"
					lower-threshold="0">
					<view class="flex flex-col items-start" style="padding: 0px 50rpx;">
						<view class="rounded-lg mb-1 flex flex-wrap" v-for="e,i in msgList" :key="i"
							style="background-color: #97B9D0;padding: 8rpx 16rpx;">
							<view class="flex" v-if="e.type=='img'">
								<text class="color-white font-sm mr-1">{{e.name}}:</text>
								<uv-image :src="e.text" width="100px" height="100px" mode="aspectFit"
									@click="lookImg(e.text)">
								</uv-image>
							</view>
							<view class="flex" v-else-if="e.type=='astrolabe'" @click="onAstrolabe(e.ids)">
								<text class="color-white font-sm mr-1" style="color:#1BADFF">{{e.name}}:</text>
								<text class="color-white font-sm mr-1" style="color:#1BADFF">{{e.text}}</text>
							</view>
							<text v-else class="font-sm"
								:style="{color:e.type=='tips'?'#1BADFF':'#fff'}">{{e.text}}</text>
						</view>
					</view>
					<view id="lastItem"></view>
				</scroll-view>
			</view>
		</view>
		<view class="pt-1 rounded-full" v-if="inputShow" style="width: 650rpx;left: 50rpx;" :style="{bottom:keyHeight}">
			<uni-easyinput type="text" v-model="msg" placeholder="说点什么" :inputBorder="false" cursorSpacing="20"
				:styles="{color:'#fff',backgroundColor: '#97B9D0'}" confirm-type="send" @confirm="sendMsg()" />
			<!-- <button size="mini" style="width:80rpx;margin-left:10px;" @click="sendMsg()">发送</button> -->
		</view>
	</view>
</template>

<script setup>
	import TencentCloudChat from '@tencentcloud/chat';
	import dayjs from "dayjs"
	import {
		nextTick,
		ref
	} from 'vue';
	const params = ref(null)

	const msg = ref("")
	const keyHeight = ref('20px')
	const msgList = ref([])
	const scrollIntoViewId = ref('')
	const scrollType = ref(true)
	const room = ref({})
	const {
		inputShow
	} = defineProps(['inputShow'])
	const warn = {
		label: "保密连麦中",
		content: '保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中保密连麦中'
	}
	let tim = null
	let fromId = ''
	// 初始化&登录
	const startChat = (options, id) => {
		console.log(id);
		params.value = options
		fromId = id
		// room.value = {
		// 	id: anchor.member.id,
		// 	name: anchor.name
		// }
		tim = getApp().globalData.tim

		// chat = TencentCloudChat.create({
		// 	SDKAppID: options.sdkAppId
		// });
		// chat.setLogLevel(1)
		// chat.registerPlugin({
		// 	'tim-upload-plugin': TIMUploadPlugin
		// });

		// chat.login({
		// 	userID: options.userId,
		// 	userSig: options.userSig,
		// }).then(res => {
		// 	console.log('登陆成功');
		// 	chat.on(TencentCloudChat.EVENT.SDK_READY, chatOn);
		// })
		// chatOn()
		tim.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, getMsg);
	}
	// 滚动至聊天底部
	const scrollToBottom = () => {
		if (scrollType.value) {
			scrollIntoViewId.value = 'lastItem'
			nextTick(() => {
				scrollIntoViewId.value = ""
			})
		}
	}
	// const chatOn = (event) => {
	// 	console.log('初始化成功，开始监听', event);
	// 	createGroup()
	// 	tim.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, getMsg);
	// }

	// // 创建聊天室
	// const createGroup = () => {

	// 	tim.createGroup({
	// 		type: TencentCloudChat.TYPES.GRP_AVCHATROOM,
	// 		name: room.value.name,
	// 		groupID: room.value.id
	// 	}).then(res => {
	// 		console.log(res);
	// 		joinGroup()
	// 	}).catch(err => {
	// 		console.log(err);
	// 		joinGroup()
	// 	})
	// }
	// 加入聊天室
	// const joinGroup = () => {
	// 	tim.joinGroup({
	// 			groupID: room.value.id
	// 		})
	// 		.then(() => {
	// 			console.log('加入聊天室')
	// 			// sendMsg(`${uni.getStorageSync('user').nickname}进入直播间`)
	// 			oncreateCustomMessage({
	// 				data: 'tips',
	// 				description: `${uni.getStorageSync('user').nickname}进入直播间`,
	// 				extension: ``
	// 			})
	// 		})
	// 		.catch(err => console.error('加入聊天室失败:', err));
	// }
	const emit = defineEmits(['custom', 'lookImg'])
	// 查看图片
	const lookImg = (url) => {
		emit('lookImg', url)
	}
	// 跳转星盘
	const onAstrolabe = (ids) => {
		console.log(ids);
		const idsArr = ids.split(',')
		uni.navigateTo({
			url: `/pages/test/astrolabe?tab=${idsArr.length>1?0:4}&ids=${ids}`
		})
	}
	// 接受消息
	const getMsg = (e) => {
		
		console.log('接受消息', e);
		e.data.forEach(a => {
			if (a.type == "TIMTextElem") {
				msgList.value.push({
					type: "text",
					text: a.payload.text,
					name: "未知",
					time: a.time
				})
			}
			if (a.type == "TIMCustomElem") {
				if (a.payload.data == 'tips') {
					// 直播间提示
					msgList.value.push({
						type: a.payload.data,
						text: a.payload.description,
					})
					emit('custom', a.payload)
				}
				if (a.payload.data == 'roomHot') emit('custom', a.payload) //更新热度
				if (a.payload.data == 'audio') emit('custom', a.payload) //设置连麦模式
				if (a.payload.data == 'astrolabe') {
					// 发送星盘
					const text = a.payload.description
					msgList.value.push({
						type: a.payload.data,
						name: text.split('&&&')[0],
						text: text.split('&&&')[1],
						ids: a.payload.extension
					})
					console.log(msgList.value);
				}
				if (a.payload.data == 'img') {
					// 发送图片
					const text = a.payload.description
					msgList.value.push({
						type: a.payload.data,
						name: text.split('***')[0],
						text: text.split('***')[1],
					})
				}
				if (a.payload.data == 'live' && a.payload.description == 'gift') {
					// 发送礼物
					const gift = JSON.parse(a.payload.extension)
					const text = gift.gift
					console.log(text);
					msgList.value.push({
						type: 'tips',
						text: `${gift.user}送出了${text.split('***')[0]}`,
					})
					emit('custom', a.payload)
				} else {
					emit('custom', a.payload)
				}
			}
		})
		scrollToBottom()
	}
	// 发送礼物
	const pushMsg = (obj) => {
		msgList.value.push(obj)
	}
	const onScroll = e => {
		if (e.detail.scrollHeight - e.detail.scrollTop < 483) {
			scrollType.value = true
		} else {
			scrollType.value = false
		}
	}
	// 发送消息
	const sendMsg = (val) => {
		const payload = {
			text: val || `${uni.getStorageSync('user').nickname}: ${msg.value}`
		}
		console.log('发送消息', val, payload.text);
		const message = tim.createTextMessage({
			to: fromId,
			conversationType: TencentCloudChat.TYPES.CONV_C2C,
			payload: payload,
		});
		tim.sendMessage(message);
		getMsg({
			data: [{
				type: "TIMTextElem",
				time: dayjs().unix(),
				payload: payload
			}]
		})
		nextTick(() => {
			msg.value = ""
		})
	}
	// 发送自定义信息 data:类型；description：信息；extension：自定义
	const oncreateCustomMessage = (payload) => {
		console.log('发送自定义信息', payload);
		// console.log(getApp().globalData.tim);
		if (payload.data == 'live' && payload.description == 'gift') {
			const gift = JSON.parse(payload.extension)
			const text = gift.gift
			pushMsg({
				type: 'tips',
				text: `${gift.user}送出了${text.split('***')[0]}`,
			})
		}
		if (payload.data == 'tips') {
			msgList.value.push({
				type: payload.data,
				text: payload.description,
			})
		}
		const message = tim.createCustomMessage({
			to: fromId,
			conversationType: TencentCloudChat.TYPES.CONV_C2C,
			payload: payload,
		});
		tim.sendMessage(message);
	}
	// 退出直播间
	const closeChat = () => {
		// if (tim) {
		// 	tim.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, getMsg)
		// 	tim.destroy()
		// }
		return true
	}
	defineExpose({
		startChat,
		closeChat,
		oncreateCustomMessage,
		getMsg,
		sendMsg
	})
</script>

<style>

</style>